﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using Hisuntech.SystemFramework.Common;

namespace Hisuntech.SystemFramework.Net
{
    ///   <summary>   
    ///   HTTP 文件下载类   
    ///   </summary>   
    public class HttpDownLoad
    {
        private long fileLength;
        private long downLength;//已经下载文件大小
        private static bool stopDown;
        public HttpDownLoad()
        {
            fileLength = 0;
            downLength = 0;
            stopDown = false;
            //   
            //   TODO:   在此处添加构造函数逻辑   
            //   
        }

        ///   <summary>   
        ///   文件下载   
        ///   </summary>   
        ///   <param   name="url">连接</param>   
        ///   <param   name="fileName">本地保存文件名</param>   
        ///   <param   name="progressBar">进度条</param>   
        ///   <param   name="label">返回已经下载的百分比</param>   
        public void httpDownFile(string url, string fileName, System.Windows.Forms.ProgressBar progressBar, Label msgLabel)
        {
            stopDown = false;
            Stream str = null, fs = null;
            byte[] mbyte = new byte[1024];
            int readL = 0;
            long lStartPos = 0;

            #region 读取http代理设置

            bool isHttpProxy = false;//标记是否使用http代理,默认false;
            WebProxy myProxy = null;

            const string UserProfile = "UserProfile.CONFIG";
            if (System.IO.File.Exists(UserProfile))
            {
                string UserProxy = XmlOperate.ReadXml("UserProxy", UserProfile).ToLower();
                if (UserProxy.ToLower() == "HTTP代理".ToLower())
                {
                    string address = XmlOperate.ReadXml("address", UserProfile);
                    string port = XmlOperate.ReadXml("port", UserProfile);
                    string username = XmlOperate.ReadXml("username", UserProfile);
                    string password = XmlOperate.ReadXml("password", UserProfile);
                    string domainname = XmlOperate.ReadXml("domainname", UserProfile);

                    myProxy = new WebProxy(address, int.Parse(port));
                    myProxy.BypassProxyOnLocal = true;
                    ICredentials credentials = new NetworkCredential(username, password, domainname);
                    myProxy.Credentials = credentials;
                    isHttpProxy = true;
                }
            }
           
            
            #endregion

            try
            {
                //获取下载文件长度   
                fileLength = getDownLength(url);
                downLength = 0;
                if (fileLength > 0)
                {
                    WebClient DownFile = new WebClient();
                    //使用代理
                    if (isHttpProxy)
                        DownFile.Proxy = myProxy;
                    str = DownFile.OpenRead(url);
                    //判断并建立文件   
                    if (!File.Exists(fileName))//if (createFile(fileName))
                    {
                        mbyte = new byte[1024];
                        readL = str.Read(mbyte, 0, 1024);
                        fs = new FileStream(fileName, FileMode.Create);
                        //读取流   
                        while (readL != 0)
                        {
                            if (stopDown)
                                break;
                            downLength += readL;//已经下载大小   
                            fs.Write(mbyte, 0, readL);//写文件   
                            readL = str.Read(mbyte, 0, 1024);//读流   
                            progressBar.Value = (int)(downLength * 100 / fileLength);
                            msgLabel.Text = progressBar.Value.ToString() + "%";
                            System.Windows.Forms.Application.DoEvents();
                        }

                        str.Close();
                        fs.Close();
                        str.Dispose();
                        fs.Dispose();
                    }
                    else
                    {
                        fs = System.IO.File.OpenWrite(fileName);
                        lStartPos = fs.Length;

                        if (lStartPos != fileLength)
                        {
                            fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
                            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                            //使用代理
                            if (isHttpProxy)
                                request.Proxy = myProxy;
      
                            if (lStartPos > 0)
                                request.AddRange((int)lStartPos);

                            System.IO.Stream ns = request.GetResponse().GetResponseStream();//向服务器请求，获得服务器回应数据流

                            mbyte = new byte[1024];
                            readL = ns.Read(mbyte, 0, 1024);
                            while (readL > 0)
                            {
                                fs.Write(mbyte, 0, readL);
                                readL = ns.Read(mbyte, 0, 1024);
                                downLength += readL;
                                progressBar.Value = (int)((downLength + lStartPos) * 100 / fileLength);
                                msgLabel.Text = progressBar.Value.ToString() + "%";
                                System.Windows.Forms.Application.DoEvents();
                            }
                            fs.Close();
                            ns.Close();
                            msgLabel.Text = "下载完成";
                        }
                        else
                        {
                            progressBar.Value = 100;
                            msgLabel.Text = "下载完成";
                            fs.Close();
                          
                        }
                    }

                    //string fileExtension = Path.GetExtension(fileName);
                    //if (fileExtension.ToLower() == ".zip")
                    //{
                    //    config.UnZip(fileName, fileName.Substring(0, fileName.LastIndexOf("/") + 1));
                    //    File.Delete(fileName);
 
                    //}

                }
            }
            catch (System.Exception ex)
            {
                if (str != null)
                    str.Close();
                if (fs != null)
                    fs.Close();
                MessageBox.Show(ex.Message);
            }
        }

        ///   <summary>   
        ///   获取下载文件大小   
        ///   </summary>   
        ///   <param   name="url">连接</param>   
        ///   <returns>文件长度</returns>   
        public long getDownLength(string url)
        {
            try
            {
                WebRequest wrq = WebRequest.Create(url);

                #region 读取http代理设置

                 const string UserProfile = "UserProfile.CONFIG";
                 if (System.IO.File.Exists(UserProfile))
                 {
                     string UserProxy = XmlOperate.ReadXml("UserProxy", UserProfile).ToLower();
                     if (UserProxy.ToLower() == "HTTP代理".ToLower())
                     {
                         string address = XmlOperate.ReadXml("address", UserProfile);
                         string port = XmlOperate.ReadXml("port", UserProfile);
                         string username = XmlOperate.ReadXml("username", UserProfile);
                         string password = XmlOperate.ReadXml("password", UserProfile);
                         string domainname = XmlOperate.ReadXml("domainname", UserProfile);

                         WebProxy myProxy = new WebProxy(address, int.Parse(port));
                         myProxy.BypassProxyOnLocal = true;
                         ICredentials credentials = new NetworkCredential(username, password, domainname);
                         myProxy.Credentials = credentials;
                         wrq.Proxy = myProxy;
                     }    

                 }
                 
                
                #endregion              

                WebResponse wrp = (WebResponse)wrq.GetResponse();
                wrp.Close();
                return wrp.ContentLength;
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(ex.Message);
                return 0;
            }
        }



        public void downClose()
        {
            stopDown = true;
        }

        ///   <summary>   
        ///   文件下载   
        ///   </summary>   
        ///   <param   name="url">连接</param>   
        ///   <param   name="fileName">本地保存文件名</param>   
        ///   <param   name="progressBar">进度条</param>   
        ///   <param   name="label">返回已经下载的百分比</param>   
        public void httpDownFile(string url, string fileName, System.Windows.Forms.ProgressBar progressBar, Label label,bool isDownde)
        {
            stopDown = false;
            Stream str = null, fs = null;
            byte[] mbyte = new byte[1024];
            int readL = 0;
            long lStartPos = 0;

            try
            {
                //获取下载文件长度   
                fileLength = getDownLength(url);
                downLength = 0;
                if (fileLength > 0)
                {
                    WebClient DownFile = new WebClient();
                    str = DownFile.OpenRead(url);
                    //判断并建立文件   
                    if (!isDownde)//if (createFile(fileName))
                    {
                        mbyte = new byte[1024];
                        readL = str.Read(mbyte, 0, 1024);
                        fs = new FileStream(fileName, FileMode.Create);
                        //读取流   
                        while (readL != 0)
                        {
                            if (stopDown)
                                break;
                            downLength += readL;//已经下载大小   
                            fs.Write(mbyte, 0, readL);//写文件   
                            readL = str.Read(mbyte, 0, 1024);//读流   
                            progressBar.Value = (int)(downLength * 100 / fileLength);
                            label.Text = progressBar.Value.ToString() + "%";
                            System.Windows.Forms.Application.DoEvents();
                        }

                        str.Close();
                        fs.Close();
                        str.Dispose();
                        fs.Dispose();
                    }
                    else
                    {
                        fs = System.IO.File.OpenWrite(fileName);
                        lStartPos = fs.Length;

                        if (lStartPos != fileLength)
                        {
                            fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
                            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                            if (lStartPos > 0)
                                request.AddRange((int)lStartPos);

                            System.IO.Stream ns = request.GetResponse().GetResponseStream();//向服务器请求，获得服务器回应数据流

                            mbyte = new byte[1024];
                            readL = ns.Read(mbyte, 0, 1024);
                            while (readL > 0)
                            {
                                fs.Write(mbyte, 0, readL);
                                readL = ns.Read(mbyte, 0, 1024);
                                downLength += readL;
                                progressBar.Value = (int)((downLength + lStartPos) * 100 / fileLength);
                                label.Text = progressBar.Value.ToString() + "%";
                                System.Windows.Forms.Application.DoEvents();
                            }
                            fs.Close();
                            ns.Close();
                            label.Text = "下载完成";
                        }
                        else
                        {
                            progressBar.Value = 100;
                            label.Text = "下载完成";
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                if (str != null)
                    str.Close();
                if (fs != null)
                    fs.Close();
                MessageBox.Show(ex.Message);
            }
        }
    }
}